import { defineStore } from 'pinia';

export const useUserStore = defineStore('user', {
    state: () => ({
        token: null,
        userrole: null,
        adminUserId: null // 存储当前登录用户的 adminUserId
    }),
    actions: {
        setToken(token) {
            this.token = token;
            localStorage.removeItem('token');
            localStorage.setItem('token', this.token);
        },
        removeToken() {
            this.token = null;
            this.userrole = null;
            this.adminUserId = null; // 清空 adminUserId
            localStorage.removeItem('token');
        },
        setUserrole(userrole) {
            this.userrole = userrole;
            localStorage.setItem('userrole', this.userrole);
        },
        setAdminUserId(adminUserId) {
            this.adminUserId = adminUserId;
            localStorage.setItem('adminUserId', this.adminUserId);
        }
    },
    getters: {
        getToken: (store) => {
            if (localStorage.getItem('token')) {
                store.token = localStorage.getItem('token');
            }
            return store.token;
        },
        getUserrole: (store) => {
            if (localStorage.getItem("userrole")) {
                store.userrole = localStorage.getItem("userrole");
                return localStorage.getItem("userrole");
            }
            return store.userrole;
        },
        getAdminUserId: (store) => {
            if (localStorage.getItem("adminUserId")) {
                store.adminUserId = parseInt(localStorage.getItem("adminUserId"), 10);
            }
            return store.adminUserId;
        }
    }
});